package com.example.demo.controller;

import com.example.demo.util.Comment;
import com.example.demo.util.Content;
import com.example.demo.util.MomentsCommentGenerator;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.imageio.ImageIO;
import javax.validation.Valid;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Base64;

@Controller
public class FormController {

    @GetMapping("/form")
    public String showForm(Model model) {
        model.addAttribute("content", new Content());
        return "form";
    }

    @PostMapping("/submit")
    public String submitForm(@Valid Content content, BindingResult contentBindingResult,
                             Model model) {
        if (contentBindingResult.hasErrors()) {
            model.addAttribute("content", content);
            return "form";
        }

        try {
            File path = new File("d:/landingsheng/upload");
            if (!path.exists()) {
                path.mkdirs();
            }
            File file = new File("d:/landingsheng/upload/" +
                    content.getImage().getOriginalFilename());
            content.getImage().transferTo(file);
            String image = MomentsCommentGenerator.getLikeImage(content,file);
            model.addAttribute("image", image);
        } catch (IOException e) {
            model.addAttribute("error", "生成图片时出错: " + e.getMessage());
        }

        return "result";
    }
}